/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.insurance.rest;

import cn.hutool.core.date.DateUtil;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.insurance.domain.InsuredApply;
import me.zhengjie.modules.insurance.handler.CaseDocsDownloadHandler;
import me.zhengjie.modules.insurance.pojo.CaseChangeUserRequest;
import me.zhengjie.modules.insurance.pojo.InsuredApplyHandlerDetailsResponse;
import me.zhengjie.modules.insurance.pojo.InsuredApplyHandlerRequest;
import me.zhengjie.modules.insurance.pojo.InsuredApplyRequest;
import me.zhengjie.modules.insurance.service.InsuredApplyService;
import me.zhengjie.modules.insurance.service.dto.InsuredApplyQueryCriteria;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author HeHui
* @date 2022-01-03
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "案件管理")
@RequestMapping("/api/insured-apply")
public class InsuredApplyController {

    private final InsuredApplyService insuredApplyService;

    private final CaseDocsDownloadHandler caseDocsDownloadHandler;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('insuredApply:list')")
    public void download(HttpServletResponse response, InsuredApplyQueryCriteria criteria) throws IOException {
        insuredApplyService.download(insuredApplyService.queryAll(criteria), response);
    }

    @GetMapping
    @ApiOperation("查询案件")
    @PreAuthorize("@el.check('insuredApply:list')")
    public ResponseEntity<Object> query(InsuredApplyQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(insuredApplyService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    /**
     * 数
     *
     * @param criteria 标准
     * @return {@link ResponseEntity}<{@link Long}>
     */
    @GetMapping("/count")
    public ResponseEntity<Long> count(InsuredApplyQueryCriteria criteria) {
        return new ResponseEntity<>(insuredApplyService.count(criteria),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增案件")
    @ApiOperation("新增案件")
    @PreAuthorize("@el.check('case:add')")
    public ResponseEntity<Void> apply(@RequestBody @Validated InsuredApplyRequest request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        insuredApplyService.apply(request, currentUserId);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    /**
     * 获取案件处理详情
     *
     * @param id id
     * @return {@link ResponseEntity}<{@link InsuredApplyHandlerDetailsResponse}>
     */
    @GetMapping("/handler")
    @ApiOperation("获取案件处理详情")
    public ResponseEntity<InsuredApplyHandlerDetailsResponse> handlerDetails(@RequestParam Long id) {
        return new ResponseEntity<>(insuredApplyService.getHandlerDetails(id), HttpStatus.OK);
    }

    /**
     * 处理
     *
     * @param request 请求
     * @return {@link ResponseEntity}<{@link Void}>
     */
    @PostMapping("/handler")
    @ApiOperation("案件处理")
    @Log("案件处理")
    public ResponseEntity<Void> handler(@RequestBody @Validated InsuredApplyHandlerRequest request) {
        insuredApplyService.handler(request, SecurityUtils.getCurrentUserId());
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @PutMapping
    @Log("修改案件")
    @ApiOperation("修改案件")
    @PreAuthorize("@el.check('case:edit','case:edit:super')")
    public ResponseEntity<Object> update(@Validated @RequestBody InsuredApplyRequest request){
        if (request.getId() == null) {
            throw new BadRequestException("缺少ID");
        }
        insuredApplyService.update(request, SecurityUtils.getCurrentUserId());
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("/update")
    @ApiOperation("加载更改数据")
    public ResponseEntity<InsuredApplyRequest> updateLoad(@RequestParam Long id) {
        return new ResponseEntity<>(insuredApplyService.loadUpdateData(id),HttpStatus.OK);
    }

    @Log("删除案件")
    @ApiOperation("删除案件")
    @PreAuthorize("@el.check('insuredApply:del')")
    //@DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        insuredApplyService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @PostMapping("/user")
    @Log("更换理赔员")
    @PreAuthorize("@el.check('case:changeUser')")
    public ResponseEntity<Void> updateUser(@RequestBody CaseChangeUserRequest request) {

        insuredApplyService.updateUser(request.getIds(), request.getResponsibleUserId(), SecurityUtils.getCurrentUserId());
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @GetMapping("/exists-next-time")
    @ApiOperation("沟通时间已存在案件统计")
    public ResponseEntity<Integer> existsNextTime(Long next) {
        if (next == null) {
            return new ResponseEntity<>(0, HttpStatus.OK);
        }
        Date date = new Date(next);
        return new ResponseEntity<>(insuredApplyService.countNextTime(DateUtil.beginOfDay(date), DateUtil.endOfDay(date), SecurityUtils.getCurrentUserId()), HttpStatus.OK);
    }


    /**
     * 下载文档
     *
     * @param id       id
     * @param response 响应
     * @return {@link ResponseEntity}<{@link ServerHttpResponse}>
     */
    @GetMapping(value = "/down-doc", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @AnonymousAccess
    public String downDoc(@RequestParam Long id, HttpServletResponse response) throws IOException {
        caseDocsDownloadHandler.down(response,id);
        return null;
    }
}